package com.example.translateappjava.Fragment;

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_MEDIA_IMAGES;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.content.Context;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.TextView;
import android.Manifest;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.example.translateappjava.Activity.HomeFragmentActivity.CalculatorActivity;
import com.example.translateappjava.Activity.HomeFragmentActivity.Forum.ForumActivity;
import com.example.translateappjava.Activity.HomeFragmentActivity.RobotActivity;
import com.example.translateappjava.Activity.HomeFragmentActivity.SelectActivity;
import com.example.translateappjava.Activity.MainActivity;
import com.example.translateappjava.Activity.ThemeUtilsActivity;
import com.example.translateappjava.Activity.MineFragmentActivity.SettingsActivity;
import com.example.translateappjava.DataBase.DatabaseHelper;
import com.example.translateappjava.Listener.LoadingProgressListener;
import com.example.translateappjava.R;
import com.example.translateappjava.Activity.HomeFragmentActivity.SearchActivity;
import com.example.translateappjava.Service.AliyunAPI.AliyunAPIHelper;
import com.example.translateappjava.Service.ChatGPT.ChatGptHelper;
import com.example.translateappjava.Service.Doubao.DoubaoVisionHelper;
import com.example.translateappjava.Service.FoodCalories.FoodCaloriesHelper;
import com.example.translateappjava.Service.FoodDetails.FoodDetailsHelper;
import com.example.translateappjava.Service.MedicalAtlas.MedicalAtlasHelper;
import com.example.translateappjava.Utils.ImageCaptureManager;
import com.example.translateappjava.Utils.ImageData;
import com.example.translateappjava.Utils.ImageRecognitionManager;
import com.google.android.material.progressindicator.CircularProgressIndicator;
import com.google.android.material.progressindicator.LinearProgressIndicator;
import java.util.ArrayList;

public class HomeFragment extends Fragment implements
        LoadingProgressListener,
        ChatGptHelper.OnChatGptResponseListener,
        AliyunAPIHelper.AliyunAPIListener,
        MedicalAtlasHelper.MedicalAtlasListener,
        FoodCaloriesHelper.FoodCaloriesListener,
        FoodDetailsHelper.FoodDetailsListener,
        DoubaoVisionHelper.DoubaoVisionListener{

    private static final int REQUEST_CAMERA_PERMISSION = 100;
    private static final int REQUEST_STORAGE_PERMISSION = 101;

    // UI Components
    private ConstraintLayout constraintLayout;
    private LinearLayout linearLayout;
    private CircularProgressIndicator circularProgressIndicator;
    private LinearProgressIndicator linearProgressIndicator;
    private View loadingOverlayContainer;
    private TextView loadingStatusTextViewOverlay;
    private TextView loadingStepDetailsTextViewOverlay;
    // Managers
    private ImageCaptureManager imageCaptureManager;
    private ImageRecognitionManager imageRecognitionManager;



    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 总是从设置中读取最新的UI版本


        // 根据UI版本选择不同的布局文件
        int layoutId = R.layout.fragment_home;
        View rootView = inflater.inflate(layoutId, container, false);

        // 初始化UI组件
        initViews(rootView);

        // 初始化管理器
        initManagers();

        // 设置事件监听器
        setupEventListeners(rootView);
        // Initially hide the new loading overlay
        if (loadingOverlayContainer != null) {
            loadingOverlayContainer.setVisibility(View.GONE);
        }
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }



    // 移除复杂的UI重建逻辑，交给MainActivity处理
    // private void recreateFragmentView() { ... } - 删除
    // private void recreateViewManually() { ... } - 删除

    private void initViews(View rootView) {
        constraintLayout = rootView.findViewById(R.id.constraintLayout);
        loadingOverlayContainer = rootView.findViewById(R.id.loading_overlay_container);
        loadingStatusTextViewOverlay = rootView.findViewById(R.id.loading_status_text_overlay);
        loadingStepDetailsTextViewOverlay = rootView.findViewById(R.id.loading_step_details_text_overlay);
        Log.d("HomeFragment", "Views initialized");
    }

    private void initManagers() {
        // 初始化图片捕获管理器
        imageCaptureManager = new ImageCaptureManager(this);

        // 初始化图片识别管理器
        imageRecognitionManager = new ImageRecognitionManager(this, getActivity());
        imageRecognitionManager.setRecognitionCompleteListener(this::onRecognitionComplete);
        imageRecognitionManager.setLoadingProgressListener(this); // Pass the listener

        Log.d("HomeFragment", "Managers initialized");
    }

    private void setupEventListeners(View rootView) {
        ImageView imageViewShot = rootView.findViewById(R.id.imageViewShot);
        SearchView searchViewSearch = rootView.findViewById(R.id.imageViewSearch);
        ImageButton caculator = rootView.findViewById(R.id.calculator);
        ImageView imageViewRobot = rootView.findViewById(R.id.imageView5);
        ImageButton select_type = rootView.findViewById(R.id.select_type);
        ImageView imageView = rootView.findViewById(R.id.imageView6); // 问问他人按钮
        // 检查控件是否存在（因为新旧UI可能有不同的控件）
        if (select_type != null) {
            select_type.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), SelectActivity.class);
                startActivity(intent);
            });
        }

        if (imageViewRobot != null) {
            imageViewRobot.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), RobotActivity.class);
                startActivity(intent);
            });
        }

        if (searchViewSearch != null) {
            searchViewSearch.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            });

            searchViewSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    Intent intent = new Intent(getActivity(), SearchActivity.class);
                    intent.putExtra("query", query);
                    startActivity(intent);
                    DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
                    databaseHelper.insertData(query);
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    return false;
                }
            });
        }

        if (caculator != null) {
            caculator.setOnClickListener(v -> {
                Intent intent = new Intent(getActivity(), CalculatorActivity.class);
                startActivity(intent);
            });
        }

        if (imageViewShot != null) {
            imageViewShot.setOnClickListener(v -> showChooseImageDialog());
        }

        // 更新这里：问问他人按钮点击跳转到论坛
        if (imageView != null) {
            imageView.setOnClickListener(v -> {
                try {
                    Intent intent = new Intent(getActivity(), ForumActivity.class);
                    startActivity(intent);

                    // 添加页面切换动画（可选）
                    if (getActivity() != null) {
                        getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                    }
                } catch (Exception e) {
                    Log.e("HomeFragment", "跳转论坛失败", e);
                    Toast.makeText(getActivity(), "暂时无法进入论坛，请稍后重试", Toast.LENGTH_SHORT).show();
                }
            });
        }

        Log.d("HomeFragment", "Event listeners set up");
    }
    private void performSampleAPIRequests() {
        try {
            // 医疗图谱请求示例
            MedicalAtlasHelper medicalAtlasHelper = new MedicalAtlasHelper(getActivity());
            medicalAtlasHelper.setMedicalAtlasListener(this);
            medicalAtlasHelper.MedicalAtlasRequest("艾滋病");

            // 食物热量请求示例
            FoodCaloriesHelper foodCaloriesHelper = new FoodCaloriesHelper(getActivity());
            foodCaloriesHelper.setFoodCaloriesListener(this);
            foodCaloriesHelper.FoodCaloriesRequest("鸡蛋");
        } catch (Exception e) {
            Log.e("HomeFragment", "API请求失败", e);
        }
    }


    private void showChooseImageDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_choose_image, null);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        dialog.show();

        Button btnCamera = dialogView.findViewById(R.id.btnCamera);
        btnCamera.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(requireContext(), CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{CAMERA}, REQUEST_CAMERA_PERMISSION);
            } else {
                imageCaptureManager.launchCamera();
            }
            dialog.dismiss();
        });

        Button btnGallery = dialogView.findViewById(R.id.btnGallery);
        btnGallery.setOnClickListener(v -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                // Android 13 及以上
                if (ContextCompat.checkSelfPermission(requireContext(), READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{READ_MEDIA_IMAGES}, REQUEST_STORAGE_PERMISSION);
                } else {
                    imageCaptureManager.launchGallery();
                }
                dialog.dismiss();
            } else {
                // Android 13 以下，使用 WRITE_EXTERNAL_STORAGE
                if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
                } else {
                    imageCaptureManager.launchGallery();
                }
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                imageCaptureManager.launchCamera();
            } else {
                Toast.makeText(getActivity(), "需要相机权限以拍摄照片", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == REQUEST_STORAGE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                imageCaptureManager.launchGallery();
            } else {
                Toast.makeText(getActivity(), "需要存储权限以访问图库", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 从ImageCaptureManager回调接收图片
    public void onImageCaptured(Bitmap bitmap) {
        onProcessingStart("正在准备图片..."); // Start loading UI
        imageRecognitionManager.processImage(bitmap);
    }

    // 从ImageRecognitionManager回调接收识别完成事件
    private void onRecognitionComplete(ArrayList<ImageData> imageDataList) {
//        onProcessingComplete(); // Hide loading UI
        Log.d("HomeFragment", "图片识别完成，共识别到 " + imageDataList.size() + " 个对象");
        // Potentially navigate to results screen or update UI here
    }
    @Override
    public void onProcessingStart(String initialMessage) {
        if (getActivity() == null) return; // Ensure fragment is attached
        getActivity().runOnUiThread(() -> {
            if (loadingOverlayContainer != null) {
                loadingStatusTextViewOverlay.setText(initialMessage);
                loadingStepDetailsTextViewOverlay.setVisibility(View.GONE); // Hide details initially
                loadingOverlayContainer.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onProgressUpdate(String message) {
        if (getActivity() == null) return;
        getActivity().runOnUiThread(() -> {
            if (loadingOverlayContainer != null && loadingOverlayContainer.getVisibility() == View.VISIBLE) {
                loadingStatusTextViewOverlay.setText(message);
                loadingStepDetailsTextViewOverlay.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onProgressUpdate(String message, String details) {
        if (getActivity() == null) return;
        getActivity().runOnUiThread(() -> {
            if (loadingOverlayContainer != null && loadingOverlayContainer.getVisibility() == View.VISIBLE) {
                loadingStatusTextViewOverlay.setText(message);
                loadingStepDetailsTextViewOverlay.setText(details);
                loadingStepDetailsTextViewOverlay.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onProcessingComplete() {
        if (getActivity() == null) return;
        getActivity().runOnUiThread(() -> {
            if (loadingOverlayContainer != null) {
                loadingOverlayContainer.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onProcessingError(String errorMessage) {
        if (getActivity() == null) return;
        getActivity().runOnUiThread(() -> {
            if (loadingOverlayContainer != null) {
                loadingOverlayContainer.setVisibility(View.GONE);
            }
            Toast.makeText(getContext(), "处理出错: " + errorMessage, Toast.LENGTH_LONG).show();
        });
    }

//    public void hideLoadingUI() {
//        if (constraintLayout != null && linearLayout != null &&
//                circularProgressIndicator != null && linearProgressIndicator != null) {
//            constraintLayout.setVisibility(View.VISIBLE);
//            linearLayout.setVisibility(View.GONE);
//            circularProgressIndicator.setVisibility(View.GONE);
//            linearProgressIndicator.setVisibility(View.GONE);
//        }
//    }

    // 接口实现方法
    @Override
    public void onChatGptResponse(String response) {
        System.out.println(response);
    }

    @Override
    public void onError(String message) {
        System.out.println(message);
    }

    @Override
    public void AliyunAPIResponse(String response, int index) {
        if (imageRecognitionManager != null) {
            imageRecognitionManager.handleAliyunAPIResponse(response, index);
        }
    }

    @Override
    public void AliyunAPIError(String message) {
        if (imageRecognitionManager != null) {
            imageRecognitionManager.handleAliyunAPIError(message);
            onProcessingError("图像识别服务出错 (Aliyun)");
        }
    }

    @Override
    public void onDoubaoVisionResponse(String response, int index) {
        if (imageRecognitionManager != null) {
            imageRecognitionManager.handleDoubaoVisionResponse(response, index);
        }
    }

    @Override
    public void onDoubaoVisionError(String error, int index) {
        if (imageRecognitionManager != null) {
            imageRecognitionManager.handleDoubaoVisionError(error, index);
            onProcessingError("图像识别服务出错 (Doubao)");
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void getFoodCaloriesResponse(String response) {

    }

    @Override
    public void getFoodDetailsResponse(String response) {

    }

    @Override
    public void onMedicalAtlasResponse(String response) {

    }

    // 简化onResume，移除重复的UI版本检查
    @Override
    public void onResume() {
        super.onResume();
    }
}